<template>
  <div>
    <!-- 搜索和操作区域 -->
    <el-card class="filter-card">
      <div class="header-section">
        <div class="title-section">
          <i class="el-icon-message" style="color: #409EFF; margin-right: 8px;"></i>
          <span class="page-title">短信模板管理</span>
        </div>
        <el-button type="primary" icon="el-icon-plus" @click="openDialog()">
          新增模板
        </el-button>
      </div>
      
      <div class="search-section">
        <el-form :inline="true" class="search-form">
          <el-form-item>
            <el-input
              v-model="search"
              placeholder="搜索模板"
              prefix-icon="el-icon-search"
              style="width: 300px;"
              @keyup.enter.native="fetchData"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="fetchData">
              搜索
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        :data="templates"
        v-loading="loading"
        class="template-table"
        stripe
        border
      >
        <el-table-column
          prop="TemplateName"
          label="模板名称"
          width="150"
        ></el-table-column>
        
        <el-table-column
          prop="ContentText"
          label="模板内容"
          min-width="200"
          show-overflow-tooltip
        ></el-table-column>
        
        <el-table-column
          prop="TemplateID"
          label="阿里云模板ID"
          width="150"
        ></el-table-column>
        
        <el-table-column
          label="短信类型"
          width="120"
        >
          <template slot-scope="scope">
            <el-tag
              :type="getMessageTypeColor(scope.row.MessageType)"
              size="small"
            >
              {{ getMessageTypeText(scope.row.MessageType) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column
          prop="CreateTime"
          label="创建时间"
          width="180"
        >
          <template slot-scope="scope">
            {{ formatDate(scope.row.CreateTime) }}
          </template>
        </el-table-column>
        
        <el-table-column
          label="操作"
          width="180"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="openDialog(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="confirmDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      :title="editingItem ? '编辑模板' : '新增模板'"
      :visible.sync="dialog"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="form"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="模板名称" prop="TemplateName">
          <el-input
            v-model="formData.TemplateName"
            placeholder="请输入模板名称"
            maxlength="20"
            show-word-limit
          ></el-input>
        </el-form-item>
        
        <el-form-item label="模板内容" prop="ContentText">
          <el-input
            type="textarea"
            v-model="formData.ContentText"
            placeholder="请输入模板内容"
            :rows="4"
            maxlength="200"
            show-word-limit
          ></el-input>
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="阿里云模板ID" prop="TemplateID">
              <el-input
                v-model="formData.TemplateID"
                placeholder="请输入模板ID"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="短信类型" prop="MessageType">
              <el-select
                v-model="formData.MessageType"
                placeholder="请选择短信类型"
                style="width: 100%;"
              >
                <el-option
                  v-for="item in MessageTypes"
                  :key="item.value"
                  :label="item.text"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog = false">取消</el-button>
        <el-button
          type="primary"
          :loading="submitting"
          @click="saveTemplate"
        >
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { SaveMessageTempalte, GetMessageTempaltePage, DeleteMessageTemplate } from '@/api/MessageTempalte'

export default {
  name: 'MessageTemplate',
  data() {
    return {
      // 短信类型选项
      MessageTypes: [
        { text: '询标', value: 0 },
        { text: '二次报价', value: 1 }
      ],
      
      // 状态变量
      search: '',
      dialog: false,
      submitting: false,
      editingItem: null,
      
      // 表单数据
      formData: {
        TemplateName: '',
        ContentText: '',
        TemplateID: '',
        MessageType: 0
      },
      
      // 表单验证规则
      formRules: {
        TemplateName: [
          { required: true, message: '请输入模板名称', trigger: 'blur' }
        ],
        ContentText: [
          { required: true, message: '请输入模板内容', trigger: 'blur' }
        ],
        TemplateID: [
          { required: true, message: '请输入模板ID', trigger: 'blur' }
        ],
        MessageType: [
          { required: true, message: '请选择短信类型', trigger: 'change' }
        ]
      },
      
      // 表格状态
      loading: false,
      templates: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      page: 1,
      totalItems: 0,
      itemsPerPage: 10
    }
  },
  mounted() {
    this.fetchData()
  },
  methods: {
    // 获取类型显示颜色
    getMessageTypeColor(type) {
      switch (type) {
        case 0: return 'primary'
        case 1: return 'success'
        case 2: return 'warning'
        default: return 'info'
      }
    },
    
    // 格式化日期
    formatDate(date) {
      return new Date(date).toLocaleString()
    },

    // 打开编辑框
    openDialog(item = null) {
      this.editingItem = item
      if (item) {
        this.formData = { 
          ...item,
          MessageType: Number(item.MessageType) 
        }
      } else {
        this.formData = {
          TemplateName: '',
          ContentText: '',
          TemplateID: '',
          MessageType: 0
        }
      }
      this.dialog = true
    },

    // 获取列表数据
    async fetchData() {
      this.loading = true
      try {
        const res = await GetMessageTempaltePage({
          pageIndex: this.currentPage,
          pageSize: this.pageSize,
          search: this.search
        })
        
        if (res.IsSuccess) {
          this.templates = res.Data.Data
          this.total = res.Data.Count
          this.totalItems = res.Data.Count
        } else {
          throw new Error(res.Message || '获取数据失败')
        }
      } catch (error) {
        console.error('获取列表失败:', error)
        this.$message.error(error.message || '获取数据失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    
    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.fetchData()
    },
    
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },

    // 保存模板
    async saveTemplate() {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return
        
        this.submitting = true
        try {
          // 准备提交的数据
          const submitData = {
            ...this.formData,
            // 如果是编辑模式，添加ID
            ...(this.editingItem && { id: this.editingItem.id }),
            TemplateID: this.formData.TemplateID,
            MessageType: parseInt(this.formData.MessageType)
          }

          // 调用保存接口
          const res = await SaveMessageTempalte(submitData)
          
          if (res.IsSuccess) {
            this.$message.success('保存成功')
            // 关闭对话框
            this.dialog = false
            // 刷新列表
            this.fetchData()
          } else {
            throw new Error(res.Message || '保存失败')
          }
        } catch (error) {
          console.error('保存失败:', error)
          this.$message.error(error.message || '保存失败')
        } finally {
          this.submitting = false
        }
      })
    },

    // 确认删除
    async confirmDelete(item) {
      this.$confirm('确定要删除这个模板吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await DeleteMessageTemplate(item.Id)
          if (res.IsSuccess) {
            this.$message.success('删除成功')
            this.fetchData()
          } else {
            throw new Error(res.Message || '删除失败')
          }
        } catch (error) {
          console.error('删除失败:', error)
          this.$message.error(error.message || '删除失败')
        }
      }).catch(() => {
        // 用户取消删除
      })
    },
    getMessageTypeText(type) {
      const map = {
        0: '询标',
        1: '二次报价'
      }
      return map[type] || '未知类型'
    }
  }
}
</script>

<style scoped>
.filter-card {
  margin-bottom: 20px;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title-section {
  display: flex;
  align-items: center;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.search-section {
  padding-top: 20px;
  border-top: 1px solid #EBEEF5;
}

.search-form {
  margin: 0;
}

.table-card {
  margin-top: 20px;
}

.template-table {
  width: 100%;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 20px;
}

.dialog-footer {
  text-align: right;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .header-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .search-form .el-form-item {
    margin-bottom: 15px;
  }
  
  .pagination-wrapper {
    padding: 10px;
  }
  
  .template-table {
    font-size: 12px;
  }
  
  .el-dialog {
    width: 90% !important;
  }
}
</style>